package com.pinecone.controller;

import java.util.List;
import java.util.Map;

import com.pinecone.common.Constant.RoleConstant;
import com.pinecone.common.annotation.CurrentUser;
import com.pinecone.common.exception.MinerException;
import com.pinecone.common.validator.group.UpdateGroup;
import com.pinecone.dto.LiveRoomDTO;
import com.pinecone.dto.LiveRoomResponseDTO;
import com.pinecone.dto.LiveRoomUpdateDTO;
import com.pinecone.dto.UserDetailsDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.pinecone.entity.LiveRoomEntity;
import com.pinecone.service.LiveRoomService;
import com.pinecone.common.utils.PageUtils;
import com.pinecone.common.utils.Query;
import com.pinecone.common.utils.R;




/**
 * 直播活动表
 * 
 * @author hushangjie
 * @email 979783618@qq.com
 * @date 2017-09-27 21:17:58
 */
@RestController
@RequestMapping("live_room")
public class LiveRoomController {

	@Autowired
	private LiveRoomService liveRoomService;

	//创建直播间
    @PreAuthorize("hasAnyRole('ROLE_ORGMASTER','ROLE_ORGHOST')")
    @PostMapping("/create")
    public R createLiveRoom(@CurrentUser UserDetailsDTO currentUser, @RequestBody @Validated LiveRoomDTO liveRoomDTO){
        String liveRoomId = liveRoomService.createLiveRoom(currentUser.getOrgId(),currentUser.getId(),liveRoomDTO);
        return R.ok().put("roomId",liveRoomId);
    }

    //获取直播间列表,返回列表数据
    @GetMapping("/list/{orgId}")
    public R getLiveRoomList(@RequestParam Map<String, Object> params
            ,@PathVariable(value = "orgId",required = true) Integer orgId){
        //根据类别获取该机构下的列表，如果不传类别参数，则获取该机构下所有直播，typeId
        //按时间排序，(全部，正在直播，类别)
        //查询列表数据
        params.put("orgId",orgId);
        Query query = new Query(params);
        if (params.get("page") != null && params.get("limit")!= null){
            List<LiveRoomResponseDTO> liveRoomList = liveRoomService.queryLiveRoomResponseList(query);
            int total = liveRoomService.queryLiveRoomResponseTotal(query);

            PageUtils pageUtil = new PageUtils(liveRoomList, total, query.getLimit(), query.getPage());

            return R.ok().put("page", pageUtil);
        }else{
            List<LiveRoomResponseDTO> liveRoomList = liveRoomService.queryLiveRoomResponseList(query);
            return R.ok().put("list", liveRoomList);
        }
    }
    //访问直播间

    //直播间广告页
    //直播间菜单
    //直播间类别
    //聊天室
    //后台控制聊天室发送消息
	/**
	 * 列表
	 */
	@PreAuthorize("hasAnyRole('ROLE_SYSADMIN')")
	@GetMapping("")
	public R list(@CurrentUser UserDetailsDTO userDetailsDTO, @RequestParam Map<String, Object> params){

		//查询列表数据
        Query query = new Query(params);
		if (params.get("page") != null && params.get("limit")!= null){
			List<LiveRoomEntity> liveRoomList = liveRoomService.queryList(query);
			int total = liveRoomService.queryTotal(query);
			
			PageUtils pageUtil = new PageUtils(liveRoomList, total, query.getLimit(), query.getPage());
			
			return R.ok().put("page", pageUtil);
		}else{
			List<LiveRoomEntity> liveRoomList = liveRoomService.queryList(query);
			return R.ok().put("list", liveRoomList);
		}
		
	}




	/**
	 * 信息
	 */
	@PreAuthorize("hasAnyRole('ROLE_ORGMASTER','ROLE_ORGHOST','ROLE_SYSADMIN')")
	@GetMapping("/info/{liveRoomId}")
	public R info(@PathVariable("liveRoomId") String liveRoomId){
		LiveRoomEntity liveRoom = liveRoomService.queryObject(liveRoomId);
		return R.ok().put("liveRoom", liveRoom);
	}
	
	/**
	 * 保存
	 */
	/*@PostMapping("")
	public R save(@RequestBody LiveRoomEntity liveRoom){
		liveRoomService.save(liveRoom);
		
		return R.ok();
	}*/

    /**
     * 更新直播
     * @param liveRoomDTO
     * @return
     */
	@PreAuthorize("hasAnyRole('ROLE_ORGMASTER','ROLE_ORGHOST')")
	@PutMapping("")
	public R update(@RequestBody @Validated({UpdateGroup.class}) LiveRoomDTO liveRoomDTO){
	    LiveRoomEntity liveRoomEntity = liveRoomService.queryObject(liveRoomDTO.getLiveRoomId());
        BeanUtils.copyProperties(liveRoomDTO,liveRoomEntity);
		liveRoomService.update(liveRoomEntity);
		
		return R.ok();
	}

    /**
     * 更新直播间简介
     * @param liveRoomUpdateDTO
     * @return
     */
    @PreAuthorize("hasAnyRole('ROLE_ORGMASTER','ROLE_ORGHOST')")
    @PutMapping("/desc")
    public R updateLiveRoomDesc(@RequestBody(required = true) @Validated LiveRoomUpdateDTO liveRoomUpdateDTO){
        LiveRoomEntity liveRoomEntity = liveRoomService.queryObject(liveRoomUpdateDTO.getLiveRoomId());
        liveRoomEntity.setEventDesc(liveRoomUpdateDTO.getEventDesc());
        liveRoomService.update(liveRoomEntity);
        return R.ok();
    }

    /**
     * 删除直播间
     * @param currentUser
     * @param liveRoomIds
     * @return
     */
    @PreAuthorize("hasAnyRole('ROLE_ORGMASTER','ROLE_ORGHOST')")
	@DeleteMapping("")
	public R delete(@CurrentUser UserDetailsDTO currentUser, @RequestBody String[] liveRoomIds){
	    if (currentUser.getRolename().equals(RoleConstant.ORGHOST)){
	        //当前操作用户是主播，只能删除自己创建的直播间
            for (String liveRoomId : liveRoomIds){
                LiveRoomEntity liveRoomEntity = liveRoomService.queryObject(liveRoomId);
                if (liveRoomEntity.getUserId() != currentUser.getId()){
                    throw new MinerException("无权操作",403);
                }
            }

        }
        if (currentUser.getRolename().equals(RoleConstant.ORGHOST)){
	        //当前操作用户是机构管理员，只能删除自己机构下的直播间
            for (String liveRoomId : liveRoomIds){
                LiveRoomEntity liveRoomEntity = liveRoomService.queryObject(liveRoomId);
                if (liveRoomEntity.getOrgId() != currentUser.getOrgId()){
                    throw new MinerException("无权操作",403);
                }
            }
        }
		liveRoomService.deleteBatch(liveRoomIds);
		
		return R.ok();
	}
	
}
